package com.mvvmhabit.org.http.interceptor

import android.text.TextUtils
import android.webkit.WebSettings
import com.mvvmhabit.org.BaseApplication
import com.mvvmhabit.org.utils.SPUtils
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @Date: 2020/11/17 12:26
 * @Author:小妖
 * @Description: 拦截器
 */
class BaseInterceptor(private val headers: Map<String, String>?) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val url = chain.request().url().toString()
        val build = chain.request().newBuilder()
        build.removeHeader("User-Agent")
        build.addHeader(
            "User-Agent",
            WebSettings.getDefaultUserAgent(BaseApplication.getInstance())
        )
        val userToken = SPUtils.getInstance()
            .getString(SPUtils.Config.USER_TOKEN, "")
        // 添加token
        if (!TextUtils.isEmpty(userToken) && !url.endsWith("/journey-auth/oauth/token")) {
            build.addHeader("Authorization", userToken)
        }
        if (headers != null && headers.isNotEmpty()) {
            headers.keys.forEach {
                build.addHeader(it, headers[it].toString()).build()
            }
        }
        return chain.proceed(build.build())
    }
}